package top.tangyh.lamp.care.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.tangyh.basic.exception.BizException;
import top.tangyh.lamp.base.entity.system.BaseRole;
import top.tangyh.lamp.base.entity.user.BaseOrg;
import top.tangyh.lamp.base.mapper.system.BaseRoleMapper;
import top.tangyh.lamp.base.mapper.user.BaseOrgMapper;
import top.tangyh.lamp.care.entity.BPgSrx;
import top.tangyh.lamp.care.entity.BPgSrxDetailNormal;
import top.tangyh.lamp.care.entity.BPgpfDept;
import top.tangyh.lamp.care.mapper.BPgSrxDetailNormalMapper;
import top.tangyh.lamp.care.mapper.BPgSrxMapper;
import top.tangyh.lamp.care.mapper.BPgpfDeptMapper;
import top.tangyh.lamp.care.mapper.BPgpfMapper;
import top.tangyh.lamp.care.service.BPgSrxService;
import top.tangyh.lamp.care.service.BPgpfService;
import top.tangyh.basic.base.service.impl.SuperServiceImpl;
import top.tangyh.lamp.care.manager.BPgpfManager;
import top.tangyh.lamp.care.entity.BPgpf;
import top.tangyh.lamp.care.vo.query.DsInVo;
import top.tangyh.lamp.care.vo.query.PgpfQueryVO;
import top.tangyh.lamp.care.vo.result.*;
import top.tangyh.lamp.care.vo.save.BPgpfSaveVO;
import top.tangyh.lamp.care.vo.save.DsPickInVO;
import top.tangyh.lamp.care.vo.update.BPgSrxUpdateVO;
import top.tangyh.lamp.care.vo.update.BPgpfUpdateVO;
import top.tangyh.lamp.care.vo.query.BPgpfPageQuery;
import top.tangyh.lamp.model.entity.base.SysRole;
import top.tangyh.lamp.model.entity.system.SysUser;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 * 业务实现类
 * 评估评分配置主表
 * </p>
 *
 * @author zqb
 * @date 2024-07-09 11:07:34
 * @create [2024-07-09 11:07:34] [zqb] [代码生成器生成]
 */
@Slf4j
@RequiredArgsConstructor
@Service
@Transactional(readOnly = true)
public class BPgpfServiceImpl extends SuperServiceImpl<BPgpfManager, Long, BPgpf> implements BPgpfService {

    private final BPgpfMapper bPgpfMapper;

    private final BPgpfDeptMapper bPgpfDeptMapper;

    private final BaseOrgMapper baseOrgMapper;

    private final BaseRoleMapper baseRoleMapper;

    private final BPgSrxService bPgSrxService;

    private final BPgSrxMapper bPgSrxMapper;


    private final BPgSrxDetailNormalMapper bPgSrxDetailNormalMapper;

    @Override
    public PageOutputDTO<PgpfDetailVo> selectPage(PgpfQueryVO queryVO) {
        List<Long> deptList = queryVO.getDeptList();
        //判断科室条件是否存在
        List<Long> pgpfIdList = null;
        if (CollectionUtil.isNotEmpty(deptList)) {
            List<BPgpfDept> yxPgDeptList = bPgpfDeptMapper.selectListByDeptIdList(queryVO.getDeptList());
            pgpfIdList = yxPgDeptList.stream().map(BPgpfDept::getPgId).collect(Collectors.toList());
        }
        //分页查询评估评分结果集
        PageHelper.startPage(queryVO.getPage(), queryVO.getSize());
        PageInfo pageInfo = new PageInfo<>(bPgpfMapper.selectListByQuery(pgpfIdList, queryVO));

        List<PgpfDetailVo> pgpfDetailVos = BeanUtil.copyToList(pageInfo.getList(), PgpfDetailVo.class);
        List<BaseOrg> listDept = baseOrgMapper.selectList(null);
        List<BaseRole> listRole = baseRoleMapper.selectList(null);
        if (CollectionUtil.isNotEmpty(pgpfDetailVos)) {
            List<Long> pgIds = pgpfDetailVos.stream().map(pgpfDetailVo -> pgpfDetailVo.getId()).collect(Collectors.toList());
            Map<Long, List<BPgpfDept>> pgDeptMap = bPgpfDeptMapper.selectListByPgids(pgIds).stream().collect(Collectors.groupingBy(BPgpfDept::getPgId, Collectors.toList()));
            pgpfDetailVos.forEach(pgpfDetailVo -> {
                if (pgDeptMap.containsKey(pgpfDetailVo.getId())) {//更新部门信息
                    pgpfDetailVo.setDeptSmallDtoList(
                            pgDeptMap.get(pgpfDetailVo.getId()).stream().map(dept -> {
                                Optional<BaseOrg> haveSysDept = listDept.stream().filter(e -> e.getId().equals(dept.getDeptId())).findFirst();
                                if (haveSysDept.isPresent()) {
                                    BaseOrg sysDept = haveSysDept.get();
                                    System.out.println("sysDept========" + sysDept);
                                    DeptSmallDto deptSmallDto =BeanUtil.toBean(sysDept, DeptSmallDto.class);
                                    return deptSmallDto;
                                }
                                return new DeptSmallDto();
                            }).collect(Collectors.toList()));
                }

                if (pgpfDetailVo.getRoleId() != null) {//更新角色信息

                    Optional<BaseRole> haveSysRole = listRole.stream().filter(e -> e.getId().equals(pgpfDetailVo.getRoleId())).findFirst();
                    if (haveSysRole.isPresent()) {
                        BaseRole sysRole = haveSysRole.get();
                        System.out.println("sysRole========" + sysRole);
                        pgpfDetailVo.setRoleSmallDto(BeanUtil.toBean(sysRole, RoleSmallDto.class) );
                    }

                }
            });

            //根据评估id查询 输入项结果集
            List<Long> pgIdList = pgpfDetailVos.stream().map(PgpfDetailVo::getId).collect(Collectors.toList());
            List<BPgSrx> yxPgSrxList = bPgSrxMapper.selectListByPgpfIdList(pgIdList);
            List<BPgSrxResultVO> srxVOList = yxPgSrxList.stream().map(BPgSrxResultVO::new).collect(Collectors.toList());
            //判断输入项不为空
            if (CollectionUtil.isNotEmpty(srxVOList)) {
                //根据输入项idList找出普通和区间 明细结果集 并按照输入项id分组
                List<Long> srxIdList = yxPgSrxList.stream().map(BPgSrx::getId).collect(Collectors.toList());
                Map<Long, List<BPgSrxDetailNormalResultVO>> srxDetailNormalMap = bPgSrxDetailNormalMapper.selectListBySrxIdList(srxIdList)
                        .stream().map(BPgSrxDetailNormalResultVO::new).collect(Collectors.groupingBy(BPgSrxDetailNormalResultVO::getPgSrxId));


                //把明细放入输入项中
                srxVOList = srxVOList.stream().peek(srxVO -> {

                    srxVO.setNormalDetailList(srxDetailNormalMap.get(srxVO.getId()));
                }).collect(Collectors.toList());
            }
            //把输入项放入评估平飞项中
            Map<Long, List<BPgSrxResultVO>> srxVOMap = srxVOList.stream().collect(Collectors.groupingBy(BPgSrxResultVO::getPgId));
            //把输入项放入评估评分Vo中
            pgpfDetailVos = pgpfDetailVos.stream().peek(pgpfVo -> {
                if (srxVOMap.containsKey(pgpfVo.getId())) {
                    pgpfVo.setSrxList(srxVOMap.get(pgpfVo.getId()));
                }
            }).collect(Collectors.toList());
            pageInfo.setList(pgpfDetailVos);
        }
        return new PageOutputDTO<>(pageInfo.getTotal(), (long) pageInfo.getPages(), (long) pageInfo.getPageNum(), pgpfDetailVos);
    }



    @Override
    public List<BPgpf> selectByRoleId(List<String> roleId) {
        LambdaQueryWrapper<BPgpf> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(BPgpf::getRoleId, roleId);
        return bPgpfMapper.selectList(wrapper);
    }

    @Override
    public List<BPgpf> selectByWithoutRoleId() {
        LambdaQueryWrapper<BPgpf> wrapper = new LambdaQueryWrapper<>();
        return bPgpfMapper.selectList(wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deletePgpfByIdList(List<Long> idList) {
        for (Long id : idList) {
            BPgpf pgpfPO = bPgpfMapper.selectById(id);
            if (null != pgpfPO) {
                pgpfPO.setIsDeleted(1);
                bPgpfMapper.updateById(pgpfPO);
            }
        }
    }

    @Override
    public BPgpf selectByPgName(String name) {
        QueryWrapper<BPgpf> wrapper = new QueryWrapper();
        wrapper.lambda().eq(BPgpf::getPgName, name).eq(BPgpf::getIsDeleted, 0);
        BPgpf yxPgpfPO = this.bPgpfMapper.selectOne(wrapper);
        return yxPgpfPO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePgpf(BPgpfUpdateVO pgpfVO) {
        BPgpf pgpfPO = bPgpfMapper.selectById(pgpfVO.getId());
        if (pgpfPO == null) {
            throw new BizException("未找到评估项");
        }
        if (!StrUtil.equals(pgpfPO.getPgName(), pgpfVO.getPgName())) {
            BPgpf yxPgpfPO = selectByPgName(pgpfVO.getPgName());
            if (yxPgpfPO != null) {
                throw new BizException("评估评分名称重复");
            }
        }
        //  BPgpf pgpfPO1 = BeanUtils.t(pgpfVO, YxPgpfPO.class);
        BPgpf pgpfPO1 = BeanUtil.toBean(pgpfVO, BPgpf.class);
        //不更新code(mybatis-plus在更新的时候做了null判断，默认不更新为null的传参)
        pgpfPO1.setPgCode(null);
        //手动触发验证
//        HandValidateUtil.valid(pgpfPO1);
        bPgpfMapper.updateById(pgpfPO1);
        //删除未包含的输入项和具体输入项明细

        BPgpfResultVO detailVo = this.selectByPgid(pgpfPO.getId());

        List<Long> oldSrxIds = detailVo.getSrxList().stream().map(BPgSrxResultVO::getId).collect(Collectors.toList());
        List<BPgSrxDetailNormal> srxDetailNormalPOS = bPgSrxDetailNormalMapper.selectListBySrxIdList(oldSrxIds);
        Map<Long, List<BPgSrxDetailNormal>> oldSrxDetails =
                srxDetailNormalPOS.stream().collect(Collectors.groupingBy(BPgSrxDetailNormal::getPgSrxId, Collectors.toList()));

        List<Long> newSrxIds = pgpfVO.getSrxList().stream().map(BPgSrxResultVO::getId).collect(Collectors.toList());
        //过滤出需要删除的输入项
        oldSrxIds.removeAll(newSrxIds);
        if (CollectionUtil.isNotEmpty(oldSrxIds)) {
            bPgSrxMapper.deleteByIds(oldSrxIds);
        }

        //所属部门更新
        bPgpfDeptMapper.deleteByPgid(pgpfVO.getId());
        List<Long> deptIds = pgpfVO.getDeptList();
        if (CollectionUtil.isEmpty(pgpfVO.getDeptList())) {
            throw new BizException("所属部门不能为空");
        }
        List<BPgpfDept> pgDeptPOS = deptIds.stream().map(deptId -> {
            BPgpfDept pgDeptPO = new BPgpfDept();
            pgDeptPO.setDeptId(deptId);
            pgDeptPO.setPgId(pgpfVO.getId());
            return pgDeptPO;
        }).collect(Collectors.toList());
        pgDeptPOS.forEach(pgDept -> {
            bPgpfDeptMapper.insert(pgDept);
        });
        //是否有输入项改变
        if (CollectionUtils.isNotEmpty(pgpfVO.getSrxList())) {
            //todo 明细id变更影响历史记录 需要判断
//            srxService.deleteByPgid(pgpfPO.getId());
//            srxDetailService.deleteByPgid(pgpfPO.getId());
            List<BPgSrxResultVO> srxList = pgpfVO.getSrxList();
            srxList.forEach(srxVO -> {
                BPgSrx pgSrxPO = BeanUtil.toBean(srxVO, BPgSrx.class);

                pgSrxPO.setPgId(pgpfPO.getId());
                if (null != pgSrxPO.getId()) {
                    LambdaUpdateWrapper<BPgSrx> srxUpdateWrapper = new LambdaUpdateWrapper<BPgSrx>();
                    srxUpdateWrapper.eq(BPgSrx::getId, pgSrxPO.getId())
                            .set(BPgSrx::getSrcL1, pgSrxPO.getSrcL1())
                            .set(BPgSrx::getSrcL2, pgSrxPO.getSrcL2())
                            .set(BPgSrx::getSrcL3, pgSrxPO.getSrcL3());
                    bPgSrxMapper.update(pgSrxPO, srxUpdateWrapper);
                } else {
                    bPgSrxMapper.insert(pgSrxPO);
                }
                //是否有输入明细项变更
                List<BPgSrxDetailNormalResultVO> normalDetailList = srxVO.getNormalDetailList();
                if (CollectionUtils.isNotEmpty(normalDetailList)) {
//                    srxDetailService.deleteBySrxid(srxVO.getId());
                    if (null != pgSrxPO.getId()) {
                        List<BPgSrxDetailNormal> oldDetailNormalPOS = oldSrxDetails.get(pgSrxPO.getId());
                        if (CollectionUtil.isNotEmpty(oldDetailNormalPOS)) {
                            List<Long> olddetailIds = oldDetailNormalPOS.stream().map(BPgSrxDetailNormal::getId).collect(Collectors.toList());
                            List<Long> newDetailIds = normalDetailList.stream().map(BPgSrxDetailNormalResultVO::getId).collect(Collectors.toList());
                            olddetailIds.removeAll(newDetailIds);
                            if (CollectionUtil.isNotEmpty(olddetailIds)) {
                                bPgSrxDetailNormalMapper.deleteByIds(olddetailIds);//剔除输入项明细
                            }
                        }
                    }
                    normalDetailList.forEach(d -> {
                        BPgSrxDetailNormal normalPO = BeanUtil.toBean(d, BPgSrxDetailNormal.class);
                        normalPO.setPgId(pgpfPO.getId());
                        normalPO.setPgSrxId(pgSrxPO.getId());
                        if (null != normalPO.getId()) {
                            bPgSrxDetailNormalMapper.updateById(normalPO);
                        } else {
                            //因为这两个选项没有 detailTypeCode输入项  所以给于默认值
                            if(srxVO.getSrxTypeCode().equals("判断")||srxVO.getSrxTypeCode().equals("区间")){
                                normalPO.setDetailTypeCode("文字");
                            }
                            if(null==normalPO.getDetailContent()){
                                normalPO.setDetailContent("");
                            }
                            bPgSrxDetailNormalMapper.insert(normalPO);
                        }
                    });
                }
            });
        }

    }


    @Override
    public BPgpfResultVO selectByPgid(Long pgid) {
        BPgpf pgpfPO = bPgpfMapper.selectById(pgid);
        if (pgpfPO == null) {
            throw new BizException("未找到评估项");
        }

        //PgpfDetailVo detailVo = ConvertUtil.convert(pgpfPO, PgpfDetailVo.class);
        BPgpfResultVO detailVo = BeanUtil.toBean(pgpfPO, BPgpfResultVO.class);


        //根据评估评分获取部门集合
        List<BPgpfDept> pgDeptPOS = bPgpfDeptMapper.selectListByPgid(pgid);
        List<Long> deptIdList = pgDeptPOS.stream().map(BPgpfDept::getDeptId).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(deptIdList)) {
            List<BaseOrg> sysDepts = baseOrgMapper.selectBatchIds(deptIdList);
            List<DeptSmallDto> deptSmallDtoList = BeanUtil.copyToList(sysDepts, DeptSmallDto.class);
            List<DeptSmallDto> deptSmallDtos = deptSmallDtoList;
            detailVo.setDeptSmallDtoList(deptSmallDtos);
            List<Long> listLong=deptSmallDtos.stream().map(DeptSmallDto::getId).collect(Collectors.toList());
            detailVo.setDeptList(listLong);
        }

        //根据角色id获取角色信息
        BaseRole sysRole = baseRoleMapper.selectById(pgpfPO.getRoleId());
        RoleSmallDto roleSmallDto = BeanUtil.toBean(sysRole, RoleSmallDto.class);
        detailVo.setRoleSmallDto(roleSmallDto);

        //根据评估评分获取输入项信息
        List<BPgSrx> pgSrxPOS = bPgSrxService.selectByPgid(pgid);
        List<BPgSrxResultVO> srxVOS = BeanUtil.copyToList(pgSrxPOS, BPgSrxResultVO.class);
        //根据输入项获取所有输入明细信息
        for (BPgSrxResultVO srxVO : srxVOS) {
            List<BPgSrxDetailNormal> detailNormalPOS = bPgSrxDetailNormalMapper.selectListBySrxId(srxVO.getId());
            List<BPgSrxDetailNormalResultVO> detailNormalVOS = BeanUtil.copyToList(detailNormalPOS, BPgSrxDetailNormalResultVO.class);
            srxVO.setNormalDetailList(detailNormalVOS);
        }
        detailVo.setSrxList(srxVOS);


        return detailVo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long addPgpf(BPgpfSaveVO pgpfVO) {
//        YxPgpfPO yxPgpfPO = selectByPgName(pgpfVO.getPgName());
        QueryWrapper<BPgpf> queryWrapper = new QueryWrapper();
        queryWrapper.eq("pg_name", pgpfVO.getPgName());
        //查询该名称是否存在
        Integer count = bPgpfMapper.selectCount(queryWrapper).intValue();

        if (count > 0) {
            throw new BizException( "评估评分已经存在:"+pgpfVO.getPgName());
        }

        BPgpf yxPgpfPO =BeanUtil.toBean(pgpfVO, BPgpf.class); ;
        //手动触发验证
//        HandValidateUtil.valid(yxPgpfPO);
        int ret = bPgpfMapper.insert(yxPgpfPO);
        final Long pgId = yxPgpfPO.getId();
        //评估与部门映射关系保存
        if (CollectionUtils.isNotEmpty(pgpfVO.getDeptList())) {
            pgpfVO.getDeptList().forEach(dept -> {
                BPgpfDept pgDeptPO = new BPgpfDept();
                pgDeptPO.setPgId(pgId);
                pgDeptPO.setDeptId(dept);
                bPgpfDeptMapper.insert(pgDeptPO);
            });
        }
        //输入项列表保存
        if (CollectionUtils.isNotEmpty(pgpfVO.getSrxList())) {
            pgpfVO.getSrxList().forEach(srxVO -> {
                BPgSrx yxPgSrxPO =BeanUtil.toBean(srxVO, BPgSrx.class);
                yxPgSrxPO.setPgId(pgId);
                int rt = bPgSrxMapper.insert(yxPgSrxPO);
                long srxId = yxPgSrxPO.getId();
                //输入项明细保存
                List<BPgSrxDetailNormalResultVO> detailList = srxVO.getNormalDetailList();
                if (CollectionUtils.isNotEmpty(detailList)) {
                    detailList.forEach(normalPO -> {
                        BPgSrxDetailNormal detailNormalPO = BeanUtil.toBean(normalPO, BPgSrxDetailNormal.class);
                        detailNormalPO.setPgSrxId(srxId);
                        detailNormalPO.setPgId(pgId);
                        if(srxVO.getSrxTypeCode().equals("判断")||srxVO.getSrxTypeCode().equals("区间")){
                            detailNormalPO.setDetailTypeCode("文字");
                        }
                        bPgSrxDetailNormalMapper.insert(detailNormalPO);
                    });
                }
            });
        }

        return yxPgpfPO.getId();
    }



}


